package com.le.edu.aop;

import com.le.edu.annotation.RedisLimitAnnotation;
import com.le.edu.exception.RedisLimitException;
import com.le.edu.resp.Result;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Le
 * @create 2024-05-26 18:31
 */
@Slf4j
@RequiredArgsConstructor
@Aspect // 定义切面
public class RedisLimitAop {
    Object result = null;

    private final StringRedisTemplate stringRedisTemplate;

    private DefaultRedisScript<Long> redisLuaScript;

    @PostConstruct
    public void init() {
        redisLuaScript = new DefaultRedisScript<>();
        redisLuaScript.setResultType(Long.class);
        redisLuaScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("rateLimiter.lua")));
    }

    @Around("@annotation(com.le.edu.annotation.RedisLimitAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint) {
        log.info("---------开始环绕通知");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        //拿到RedisLimitAnnotation注解，如果存在则说明需要限流，容器捞鱼思想
        RedisLimitAnnotation redisLimitAnnotation = method.getAnnotation(RedisLimitAnnotation.class);
        if (redisLimitAnnotation != null) {
            //获取redis中的key
            String key = redisLimitAnnotation.key();
            String className = method.getDeclaringClass().getName();
            String methodName = method.getName();

            String limitKey = key + "\t" + className + "\t" + methodName;
            log.info("Redis限流的key：{}", limitKey);

            if (null == key) {
                throw new RedisLimitException("it's danger,limitKey cannot be null");
            }
            long limit = redisLimitAnnotation.permitsPerSecond();
            long expire = redisLimitAnnotation.expire();
            List<String> keys = new ArrayList<>();
            keys.add(key);

            Long count = stringRedisTemplate.execute(redisLuaScript, keys, String.valueOf(limit), String.valueOf(expire));
            if (count != null && count == 0) {
                log.info("Redis限流了,key:{}", key);
                return Result.fail(redisLimitAnnotation.msg());
            }
        }

        try {
            result = joinPoint.proceed();  //放行
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        log.info("---------结束环绕通知");
        return result;
    }
}
